package com.wedjg.concurrency.example.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author wedjg
 * @version 1.0
 * @date 2019/6/4
 */
public class CountDownLatchExnaple2 {

    private static final int THREAD_COUNT = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadNumber = i;
            executorService.execute(()->{
                try {
                    test(threadNumber);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 每一条线程执行完test()后把countDownLatch减一
                    countDownLatch.countDown();
                }
            });
        }
        //等到countDownLatch为0，或者等待10毫秒后，await()后面的语句才执行
        countDownLatch.await(10, TimeUnit.MILLISECONDS);
        System.out.println("结束了");
        executorService.shutdown();

    }

    public static void test(int threadNumber) throws Exception {
        Thread.sleep(100);
        System.out.println("线程ID为：" + threadNumber);
    }

}
